package com.youi.shop.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youi.shop.commons.exceptions.GlobalException;
import com.youi.shop.commons.result.StatusCode;
import com.youi.shop.commons.utils.SnowflakeIdUtils;
import com.youi.shop.mapper.*;
import com.youi.shop.pojo.entity.*;
import com.youi.shop.pojo.qo.order.OrderCreateQO;
import com.youi.shop.pojo.vo.address.MemberAddressVO;
import com.youi.shop.pojo.vo.order.OrderVO;
import com.youi.shop.service.OrderService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author xxf
 * @since 2020-11-09
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Resource
    OrderMapper orderMapper;

    @Resource
    CompanyAddressMapper companyAddressMapper;

    @Resource
    CartMapper cartMapper;

    @Resource
    ProductMapper productMapper;

    @Resource
    OrderItemMapper orderItemMapper;

    /**
     * 创建订单
     * @param orderCreateQO
     * @return
     */
    @Transactional
    @Override
    public OrderVO createOrder(OrderCreateQO orderCreateQO) {
        //提交结算购物车---》生成一张订单
        //1.生成订单号--》雪花
        String orderSn = "" + new SnowflakeIdUtils(3, 1).nextId();
        //2.获取提交的购物车信息
        List<Cart> cartList = cartMapper.selectByMemberId(orderCreateQO.getMemberId());

        //3.判断库存是否足够，计算总金额total

        BigDecimal total = new BigDecimal(0);
        for (Cart cart : cartList) {
            Product product = productMapper.selectById(cart.getProductId());
            //库存 < 购买数量
            if (product.getProductStock() < cart.getQuantity()) {
                //抛出异常
                throw new GlobalException(StatusCode.UNDERSTOCK_ERROR);
            }
            //3.计算总金额  该会员提交的购物车小计总和
            total = total.add(cart.getTotalAmount());

        }

        //4.订单写入数据库
        Order order = new Order();
        order.setMemberId(orderCreateQO.getMemberId());
        order.setAddressId(orderCreateQO.getAddressId());
        order.setOrderSn(orderSn);
        order.setTotalAmount(total);
        order.setPayType(orderCreateQO.getPayType());
        order.setStatus(0);
        order.setNote(orderCreateQO.getNote());





       //插入返回主键传给item对象
        orderMapper.insertOrder(order);
//        System.out.println("================================================");
//        System.out.println("order.getOrderId():"+);
//        System.out.println("orderId:"+orderId);
//        System.out.println("================================================");
        //5.将购物车信息转成订单项
        List<OrderItem> list = new ArrayList<>();
        for (Cart cart : cartList) {
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderId(order.getOrderId());
            orderItem.setProductId(cart.getProductId());
            orderItem.setQuantity(cart.getQuantity());
            orderItem.setCount(cart.getTotalAmount());
            orderItem.setProduct(cart.getProduct());
            list.add(orderItem);
        }

        //6.订单项写入数据库
//        orderItemMapper.insertBatch(list);
        for (OrderItem orderItem : list) {
            orderItemMapper.insert(orderItem);
        }


        //订单对象里的订单项对象
        order.setOrderItems(list);
        CompanyAddress address = companyAddressMapper.selectById(order.getAddressId());
        //地址对象
        order.setAddresses(address);


        //创建vo对象
        OrderVO orderVO = new OrderVO();
        orderVO.setMemberId(order.getMemberId());
        orderVO.setAddressId(order.getAddressId());
        orderVO.setOrderSn(order.getOrderSn());
        orderVO.setTotalAmount(order.getTotalAmount());
        orderVO.setPayType(order.getPayType());
        orderVO.setStatus(order.getStatus());
        orderVO.setNote(order.getNote());
        //地址
        MemberAddressVO memberAddressVO = new MemberAddressVO();
        BeanUtils.copyProperties(order.getAddresses(), memberAddressVO);
        orderVO.setMemberAddressVO(memberAddressVO);

        //订单项
        orderVO.setOrderItems(list);





        //8.清空购物车
        QueryWrapper<Cart> wrapper = new QueryWrapper<>();
        wrapper.eq("member_id", orderCreateQO.getMemberId());
        cartMapper.delete(wrapper);
        return orderVO;
    }

    /**
     * 根据用户名查询订单
     * @param memberId
     * @return
     */
    @Override
    public List<OrderVO> selectByMemberId(Long memberId) {
        //联合查询返回订单表与地址表信息
        List<Order> orderList = orderMapper.selectByMemberId(memberId);
        List<OrderVO> list = new ArrayList<>();
        OrderVO orderVO= null;
        //循环 遍历  取值
        for (Order order : orderList) {
            orderVO = new OrderVO();
            BeanUtils.copyProperties(order, orderVO);
            list.add(orderVO);
        }
        return list;
    }

    /**
     * 根据订单id查询订单详细信息
     * @param orderId
     * @return
     */
    @Override
    public OrderVO selectByOrderId(Long orderId) {
        //订单详细信息包含订单项
        Order order = orderMapper.selectByOrderId(orderId);
        List<OrderItem> list = orderItemMapper.selectByOrderId(orderId);
//        order.setOrderItems(list);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(order, orderVO);
        orderVO.setOrderItems(list);
        return orderVO;
    }
}
